//组合用户相关的状态
import { createSlice } from '@reduxjs/toolkit'
import { removeToken, removeUserInfo } from '@/utils'
import { setToken as _setToken, getToken } from '@/utils'
import { setUserInfo as _setUserInfo, getUserInfo } from '@/utils'
import { message } from 'antd'
import { loginAPI } from '@/apis/user'

const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken() || '',
    userInfo: getUserInfo() || {},
    code: ''
  },
  // 同步修改方法
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      //localStorage保存token
      _setToken(action.payload)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
      _setUserInfo(action.payload)
    },
    clearUserdata(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
      removeUserInfo()
    },
    setCode(state, action) {
      //保存登录时返回的状态码
      state.code = action.payload
    }
  }
})

// 解构出actionCreater
const { setToken, setUserInfo, clearUserdata, setCode } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步方法封装
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(loginForm)
    if (res.code === 10000 || '') {      
      dispatch(setToken(res.msg))
      const {username:userName,userImg,userId} = res.data
      const userfile = {userName,userImg,userId}
      dispatch(setUserInfo(userfile))
      message.success('恭喜登录成功')
    } else {
      dispatch(clearUserdata())
      message.warning('登录失败--请重试')
    }
    dispatch(setCode(res.code))
  }
}

export { fetchLogin, setToken, setUserInfo, clearUserdata, setCode }

export default userReducer